package com.fastgeek.platform.db.datasource;


import java.sql.Connection;
import java.sql.SQLException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
import com.fastgeek.platform.db.datasource.config.*;
/**
 * @Title DefaultDataSourceFactory.java
 * @author zhangliang
 * @Description:
 * @version $Rev$
 * @LastModify: $Id$
 */
public class DataSourceFactory {
	private static DataSourceFactory dataSourceFactory;
	private Map<String, DataSourceMeta> dsMap = new ConcurrentHashMap<String, DataSourceMeta>();
	private Map<String, DBConfig> mapConfig;
	private String defaultDsName;
	private IDataSource provider;

	private String config;
	private IXmlParser dbXmlParser;
	private IXmlParser providerParse;

	private DataSourceFactory() {
	}

	public static DataSourceFactory getInstance() {
		if (dataSourceFactory == null) {
			dataSourceFactory = new DataSourceFactory();
		}
		return dataSourceFactory;
	}

	public void setConfig(String config) {
		this.config = config;
	}

	public void setDbXmlParser(IXmlParser dbXmlParser) {
		this.dbXmlParser = dbXmlParser;
	}

	public void setProviderParse(IXmlParser providerParse) {
		this.providerParse = providerParse;
	}

	public void start() {
		mapConfig = dbXmlParser.load(config);
		Map providerMap = providerParse.load(config);
		try {
			provider = (IDataSource) Class.forName(
					(String) providerMap.get("provider")).newInstance();
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}

		for (Entry<String, DBConfig> tmpDbConfig : mapConfig.entrySet()) {
			String name = tmpDbConfig.getKey();
			DBConfig tmpConfig = tmpDbConfig.getValue();
			if (tmpConfig.isDefault())
				defaultDsName = name;
			DataSourceMeta tmpMeta = new DataSourceMeta(name,
					provider.loadSource(tmpConfig));
			dsMap.put(name, tmpMeta);
		}
	}

	public void stop() {
		dsMap.clear();
	}

	public DataSourceMeta getDataSourceMeta(String ds) {
		return dsMap.get(ds);
	}

	public DataSourceMeta getDefaultDataSourceMeta() {
		return getDataSourceMeta(defaultDsName);
	}
	
	public static void main(String[] args) throws SQLException {
		DataSourceFactory dataSourceFactory = DataSourceFactory.getInstance();
		dataSourceFactory.setConfig("db.xml");
		dataSourceFactory.setDbXmlParser(new DBXmlParser());
		dataSourceFactory.setProviderParse(new ProviderParser());
		dataSourceFactory.start();
		DataSourceMeta meta = DataSourceFactory.getInstance()
		.getDataSourceMeta("mysql_platform");
		Connection con = meta.getConnection();
		System.out.println(con.getMetaData().getDatabaseProductName());
	}
}
